import {
  _decorator,
  AnimationClip,
  Component,
  Animation,
  Node,
  resources,
  Sprite,
  SpriteFrame,
  Color,
  UITransform,
  AnimationState,
} from "cc";
const { ccclass, property } = _decorator;

import { Kit } from "./../Kits/Kit";
import { STEADY_VALUE } from "../Kits/SteadyValues";

/**
 * 帧动画: 通过一系列连续的静态图像（帧）快速播放来营造出动画效果的
 */
@ccclass("Animation01")
export class Animation01 extends Component {
  @property
  frameRate: number = 10;

  @property
  clipDuration: number = 1;

  @property
  wrapMode: AnimationClip.WrapMode = AnimationClip.WrapMode.Normal;

  @property
  clipName: string = "TheClip";

  @property
  imgFolderPath: string;

  @property([SpriteFrame])
  spriteFrameArray: SpriteFrame[];

  @property
  localNode: Node;

  @property
  isPlayingAnimation: boolean = true;

  animationComponent: Animation;

  kit: Kit = Kit.getInstance();

  async animationInitialize() {
    this.spriteFrameArray = await this.kit.loadImages(this.imgFolderPath);
    this.initilization();

    this.localNode.addComponent(Animation);
    this.animationComponent = this.localNode.getComponent(Animation);

    this.playingAnimation();
  }

  checkOutAnimationPlay() {
    if (this.isPlayingAnimation) {
      this.animationComponent.resume();
    } else if (!this.isPlayingAnimation) {
      this.animationComponent.pause();
    }
  }

  initilization() {
    this.localNode.addComponent(Sprite);
    const spriteComponent = this.localNode.getComponent(Sprite);

    const newColor = new Color(255, 255, 255);
    spriteComponent.color = newColor;

    this.localNode.addComponent(UITransform);
    const transform = this.localNode.getComponent(UITransform);
    transform.setContentSize(
      STEADY_VALUE.FIRST.WIDTH,
      STEADY_VALUE.FIRST.HEIGHT
    ); // 设置宽高
  }

  playingAnimation() {
    let clip1 = AnimationClip.createWithSpriteFrames(
      this.spriteFrameArray,
      this.frameRate
    );
    clip1.name = this.clipName;
    clip1.wrapMode = this.wrapMode;
    clip1.duration = this.clipDuration;

    this.animationComponent.addClip(clip1);
    this.animationComponent.play(this.clipName);
  }

  protected start(): void {
    console.log(this.constructor.name);
  }
}
